package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.*;
import com.example.transaction.sys.service.IAddressService;
import com.example.transaction.sys.service.ICommentService;
import com.example.transaction.sys.service.IItemService;
import com.example.transaction.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zh
 * @since 2023-06-20
 */
@RestController
@RequestMapping("/sys/comment")
public class CommentController {

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IItemService itemService;

    @CacheEvict(value = "comments", allEntries = true)
    @PostMapping
    public Result<String> addComment(@RequestBody Comment comment){
        try {
            commentService.save(comment);
        }catch (Exception e){
            return Result.fail("评论新建失败");
        }
        return Result.success("评论添加成功");
    }

    /**
     * 根据评论id删除评论
     * @param commentid
     * @return
     */
    @CacheEvict(value = "comments", allEntries = true)
    @DeleteMapping("/{commentid}")
    public Result<Comment>deleteCommentById(@PathVariable("commentid")Integer commentid){
        commentService.removeById(commentid);
        return Result.success("删除评论成功");
    }

    /**
     * 根据评论id得到评论
     * @param commentid
     * @return
     */
    @GetMapping("/getCommentByCommentID/{commentid}")
    public Result<Comment>getCommentById(@PathVariable("commentid")Integer commentid){
        Comment comment=commentService.getById(commentid);
        return Result.success(comment);
    }

    /**
     * 根据userid得到评论
     * @param userid
     * @return
     */
    @GetMapping("/getCommentByUserID/{userid}")
    public Result<List<Comment>>getCommentByUserID(@PathVariable("userid")String userid){
        List<Comment> comments=commentService.getCommentByUserID(userid);
        return Result.success(comments);
    }

    /**
     * 根据username得到评论
     * @param username
     * @return
     */
    @GetMapping("/getCommentByUserName/{username}")
    public Result<List<Comment>>getCommentByUserName(@PathVariable("username")String username){
        List<Comment> comments=commentService.getCommentByUserName(username);
        return Result.success(comments);
    }

    /**
     * 查询所有评论，或者按条件查询
     * @param
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Cacheable(value = "comments", key = "'allcomments'+#itemName+#commentName+#sellerName+#pageNo+#pageSize")
    @GetMapping("/list")
    public Result<Map<String,Object>>getCommentList(@RequestParam(value = "itemName",required = false)String itemName,
                                                 @RequestParam(value = "commenterName",required = false)String commentName,
                                                 @RequestParam(value = "sellerName",required = false)String sellerName,
                                                 @RequestParam(value = "pageNo")Long pageNo,
                                                 @RequestParam(value = "pageSize")Long pageSize){
        LambdaQueryWrapper<Comment> wrapper=new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(itemName)) {
            List<Integer> itemIds = itemService.getItemIdsByItemNameLike(itemName);
            if (!itemIds.isEmpty()) {
                wrapper.in(Comment::getItemID, itemIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }

        if (StringUtils.hasLength(commentName)) {
            List<Integer> commentIds = userService.getUserIdsByUsernameLike(commentName);
            if (!commentIds.isEmpty()) {
                wrapper.in(Comment::getUserID, commentIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }

        if (StringUtils.hasLength(sellerName)) {
            List<Integer> itemIds = commentService.getItemIdsByUsernameLike(sellerName);
            if (!itemIds.isEmpty()) {
                wrapper.in(Comment::getItemID, itemIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }

        Page<Comment> page=new Page<>(pageNo,pageSize);
        commentService.page(page,wrapper);

        List<Comment> commentList = page.getRecords();
        List<Map<String, Object>> rows = new ArrayList<>();

        for (Comment comment :  commentList) {
            Map<String, Object> row = new HashMap<>();
            row.put("commentID", comment.getCommentID());
            row.put("commentContent", comment.getCommentContent());
            row.put("commentTime", comment.getCommentTime());
            row.put("itemID", comment.getItemID());
            row.put("userID", comment.getUserID());
            row.put("itemName", itemService.getById(comment.getItemID()).getItemName());
            row.put("commenterName", userService.getById(comment.getUserID()).getUsername());
            row.put("sellerID", itemService.getById(comment.getItemID()).getUserID());
            row.put("sellerName", userService.getById(itemService.getById(comment.getItemID()).getUserID()).getUsername());
            rows.add(row);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", rows);
        return Result.success(data);
    }

}
